//---------------------------------------------------------------------------

#pragma hdrstop

#include "my_protocol.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)



DWORD GetPacketType(void *buff,u_long datalen)
{
	if(datalen<sizeof(DWORD)) return PACKET_UNKNOWN;
	return *((DWORD*)buff);
}

bool ParcePacket(void *buff,u_long datalen,void *outstruct)
{
	if(datalen<sizeof(DWORD)) return false;
	DWORD packettype=*((DWORD*)buff);
	datalen-=sizeof(DWORD);
	++(DWORD*)buff;

	switch(packettype)
	{
		case PACKET_CMD:
			memcpy(outstruct,buff,sizeof(DWORD)*2);
			++(DWORD*)buff;
			((CmdPacket*)outstruct)->data=new BYTE[*((DWORD*)buff)];
			memcpy(((CmdPacket*)outstruct)->data,(DWORD*)buff+1,*((DWORD*)buff));
		break;
		case PACKET_TELNET:
			memcpy(outstruct,buff,sizeof(DWORD));
			((TelnetPacket*)outstruct)->str=new char[*((DWORD*)buff)];
			memcpy(((TelnetPacket*)outstruct)->str,(DWORD*)buff+1,*((DWORD*)buff));
		break;
		default: return false;
	};
	return true;
}

DWORD BuildPacket(DWORD packettype,void *inputstruct,void *outbuff)
{
	memcpy(outbuff,&packettype,sizeof(DWORD));
	++(DWORD*)outbuff;

	switch(packettype)
	{
		case PACKET_CMD:
			memcpy(outbuff,inputstruct,sizeof(DWORD)*2);
			memcpy((DWORD*)outbuff+2,((CmdPacket*)inputstruct)->data,((CmdPacket*)inputstruct)->datalen);
			return 12+((CmdPacket*)inputstruct)->datalen;
		case PACKET_TELNET:
			memcpy(outbuff,inputstruct,sizeof(DWORD));
			memcpy((DWORD*)outbuff+1,((TelnetPacket*)inputstruct)->str,((TelnetPacket*)inputstruct)->datalen);
			return 8+((TelnetPacket*)inputstruct)->datalen;
		default: return false;
	};
}
